package com.yupi.springbootinit.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yupi.springbootinit.mapper.DeviceInfoMapper;
import com.yupi.springbootinit.model.entity.DeviceInfo;
import com.yupi.springbootinit.service.DeviceInfoService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

@Service
public class DeviceInfoServiceImpl extends ServiceImpl<DeviceInfoMapper, DeviceInfo> implements DeviceInfoService {

    @Override
    public boolean create(DeviceInfo device) {
        validate(device, true);
        // IP 唯一
        long exists = this.count(new LambdaQueryWrapper<DeviceInfo>().eq(DeviceInfo::getIpAddress, device.getIpAddress()));
        if (exists > 0) {
            throw new IllegalArgumentException("IP 已存在");
        }
        return this.save(device);
    }

    @Override
    public boolean update(DeviceInfo device) {
        validate(device, false);
        if (device.getId() == null) {
            throw new IllegalArgumentException("ID 不能为空");
        }
        // 更新时校验 IP 唯一（排除自身）
        long exists = this.count(new LambdaQueryWrapper<DeviceInfo>()
                .eq(DeviceInfo::getIpAddress, device.getIpAddress())
                .ne(DeviceInfo::getId, device.getId()));
        if (exists > 0) {
            throw new IllegalArgumentException("IP 已存在");
        }
        return this.updateById(device);
    }

    @Override
    public boolean remove(Integer id) {
        if (id == null) {
            throw new IllegalArgumentException("ID 不能为空");
        }
        return this.removeById(id);
    }

    private void validate(DeviceInfo device, boolean creating) {
        if (device == null) {
            throw new IllegalArgumentException("参数不能为空");
        }
        if (!StringUtils.hasText(device.getDeviceName())) {
            throw new IllegalArgumentException("设备名称不能为空");
        }
        if (!StringUtils.hasText(device.getIpAddress())) {
            throw new IllegalArgumentException("设备IP不能为空");
        }
    }
}